package dealfinder

class UserController extends RootController {

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [userInstanceList: User.list(params), userInstanceTotal: User.count()]
    }

    def create = {
        def userInstance = new User()
        userInstance.properties = params
        return [userInstance: userInstance]
    }

    def save = {
        def userInstance = new User(params)
        if (userInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])}"
            redirect(action: "show", id: userInstance.id)
        }
        else {
            render(view: "create", model: [userInstance: userInstance])
        }
    }

    def show = {
        def userInstance = User.get(params.id)
        if (!userInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])}"
            redirect(action: "list")
        }
        else {
            [userInstance: userInstance]
        }
    }

    def edit = {
        def userInstance = User.get(params.id)
        if (!userInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [userInstance: userInstance]
        }
    }

    def update = {
        def userInstance = User.get(params.id)
        if (userInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (userInstance.version > version) {
                    
                    userInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'user.label', default: 'User')] as Object[], "Another user has updated this User while you were editing")
                    render(view: "edit", model: [userInstance: userInstance])
                    return
                }
            }
            userInstance.properties = params
            if (!userInstance.hasErrors() && userInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])}"
                redirect(action: "show", id: userInstance.id)
            }
            else {
                render(view: "edit", model: [userInstance: userInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def userInstance = User.get(params.id)
        if (userInstance) {
            try {
                userInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'user.label', default: 'User'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'user.label', default: 'User'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])}"
            redirect(action: "list")
        }
    }
    /*Method for creating a user and assigning the user a Deal.
     *The method will do appropriate action after the user is added to the 
     *Deal.  
     *
     *@param firstName
     *@param lastName
     *@param phoneNumber
     *@param dealId
     */
    def submitDeal = {
        println(params)
        Map map = new HashMap()
        if(params.dealId != ""){
            println("dealId valid")
            Deal deal = Deal.findWhere(id: params.dealId.toLong())
        User user = new User(firstName: params.firstName, lastName: params.lastName, phoneNumber: params.phoneNumber.toInteger()).save(flush:true)
        deal.checkValid();
        
        if(deal != null && deal.active){
            deal.addToUsers(user)
            println("adds user to deal")
            if(deal.save(flush: true)){
                if(deal.users.size() == deal.maxUsers){
                    deal.active = false;
                }
                if(deal.users.size() == deal.minUsers){
                    //Send invites to all users
                    println("invites to all users")
                    map.result = "Your coupom has been sent"
                    if(Coupon.generateAllCoupons(deal)){
                        println("send coupon")
                        map.result = "Your coupon has been sent"
                    }
                }
                else if(deal.users.size() > deal.minUsers) {
                    //send invite only to the last added user
                    println("send coupon to last added user")
                    map.result = "Your coupon has been sent!"
                    if(Coupon.generateSingleCoupon(deal, user)){
                        println("coupon sent")
                        map.result = "Your coupon has been sent"
                    }
                }
                else{
                  println("waiting for others")
                map.result = "You will receive your coupon as soon as the deal has been validated"  
                } 
            }
            else {
                map.result = "Something bad has happened"
                println("something wrong has happened")
            }
        }
        else{
            map.result = "Sorry, the deal is not valid"
        }
       }
        else{
            map.result = "Sorry, the deal is no longer valid"
        }
        setResult(map)
    }
}
